﻿using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using tenpayApp;

namespace EmoneyWeiXinBLL
{
    public class WeiXinPayBLL
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="shh">商户号</param>
        /// <param name="openid"></param>
        /// <param name="t_money"></param>
        /// <param name="t_order_no"></param>
        /// <param name="wxInfo"></param>
        /// <param name="sendRetMsg"></param>
        /// <returns></returns>
        public static string sendRedBag(SendRedPackConfig srpConfig, string openid, double t_money, out string t_order_no, out string sendRetMsg)
        {
            //sendRetMsg = "成功";
            //return "";
            //  MyTrace.get().debug("QPayBLL.sendRedBag.begin", openid, t_money.ToString(), t_order_no);
            string sendRetCode = ""; //返回码
            sendRetMsg = "";
            string pre_mch_billno = "";
            string pre_mch_id = srpConfig.mch_id;
            string pre_wxappid = srpConfig.wxappid;
            string pre_total_amount = t_money.ToString();
            string pre_re_openid = openid;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");
            pre_mch_billno = DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(10);
            pre_mch_billno = srpConfig.mch_id + pre_mch_billno;
            t_order_no = pre_mch_billno;
            //return "";
            try
            {
                //创建支付应答对象
                RequestHandler packageReqHandler = new RequestHandler();
                packageReqHandler.init();
                //设置package订单参数
                packageReqHandler.setParameter("nonce_str", TenpayUtil.getNoncestr());		//nonce_str
                packageReqHandler.setParameter("mch_billno", pre_mch_billno);		//商家订单号
                packageReqHandler.setParameter("mch_id", pre_mch_id);		  //商户号
                packageReqHandler.setParameter("wxappid", pre_wxappid);		  //商户公众号appid
                packageReqHandler.setParameter("nick_name", srpConfig.title);		  //提供方名称
                packageReqHandler.setParameter("send_name", srpConfig.title);		  //商户名称
                packageReqHandler.setParameter("re_openid", pre_re_openid);		  //openid
                packageReqHandler.setParameter("total_amount", pre_total_amount);		  //付款金额
                packageReqHandler.setParameter("min_value", pre_total_amount);		  //最小红包
                packageReqHandler.setParameter("max_value", pre_total_amount);		  //最大红包
                packageReqHandler.setParameter("total_num", "1");		  //红包发放人数
                packageReqHandler.setParameter("wishing", srpConfig.wishing);		  //红包祝福语 128
                packageReqHandler.setParameter("client_ip", "192.168.6.117");		  //调用方IP地址
                packageReqHandler.setParameter("act_name", srpConfig.act_name);		  //活动名称32
                packageReqHandler.setParameter("remark", srpConfig.remark);		  //活动备注256
                //packageReqHandler.setParameter("logo_imageurl", "");		  //活动LOGO URL http://ds.emoney.cn/chaoguquan/images/jp.png
                packageReqHandler.setParameter("share_content", srpConfig.share_content);		  //分享文案
                packageReqHandler.setParameter("share_url", Config.Host_Url + "Bag2/Index?p_openid=" + openid);		  //分享地址OAuth2Helper.GetAuthorizeUrl(ConfigHelper.Host_Url + "Bag2/Index?p_openid=" + openid,false)
                packageReqHandler.setParameter("share_imgurl", Config.Host_Url + "images/jp.png");//分享LOGO
                packageReqHandler.setKey(srpConfig.paykey);
                string data = packageReqHandler.getXMLData();
                // MyTrace.get().debug("红包debug002");
                string ret = NetHelper.LoadDataPostWithCert(Config.api_redbag_url, null, data, Encoding.GetEncoding("UTF-8"), pre_mch_id,srpConfig.wechat_bag_cert);
                // MyTrace.get().debug("ret:" + ret);
                RequestHandler responseHandler = new RequestHandler();
                responseHandler.setKey(srpConfig.paykey);
                DataSet ds = Common.GetDataSetByXmlData(ret);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        responseHandler.setParameter(dt.Columns[i].ColumnName, dt.Rows[0][i].ToString());
                    }
                }
                ds.Clear(); ds = null;
                //判断协议字段
                string return_code = responseHandler.getParameter("return_code");
                if (return_code != null)
                {
                    if (return_code == "SUCCESS")
                    {
                        ////校验签名
                        //string check_msg = "";
                        //if (responseHandler.checkSign(out check_msg))
                        //{
                        string result_code = responseHandler.getParameter("result_code");
                        if (result_code != null)
                        {
                            if (result_code == "SUCCESS")
                            {
                                string mch_billno = responseHandler.getParameter("mch_billno", false);
                                string mch_id = responseHandler.getParameter("mch_id", false);
                                string wxappid = responseHandler.getParameter("wxappid", false);
                                string re_openid = responseHandler.getParameter("re_openid", false);
                                string total_amount = responseHandler.getParameter("total_amount", false);
                                if (pre_mch_billno == mch_billno && pre_mch_id == mch_id && pre_wxappid == wxappid && pre_re_openid == re_openid && pre_total_amount == total_amount)
                                {
                                    sendRetCode = "";
                                    sendRetMsg = "success";
                                }
                                else
                                {
                                    sendRetCode = "10013";//me
                                    sendRetMsg = "返回参数有变更";
                                }
                            }
                            else
                            {
                                sendRetCode = responseHandler.getParameter("err_code", false);
                                sendRetMsg = responseHandler.getParameter("err_code_des", false);
                            }
                        }
                        else
                        {
                            sendRetCode = "10012";//me
                            sendRetMsg = "找不到result_code";
                        }
                    }
                    else
                    {
                        sendRetCode = return_code;
                        sendRetMsg = responseHandler.getParameter("return_msg", false);
                    }
                }
                else
                {
                    sendRetCode = "10011";//me
                    sendRetMsg = "找不到return_code";
                }
            }
            catch (Exception ex)
            {
                sendRetCode = "10014";//me
                sendRetMsg = ex.Message;
            }
            return sendRetCode;
        }

        public static string sendRedBag(SendRedPackConfig srpConfig, string openid, double t_money,  string t_order_no, out string sendRetMsg)
        {
            //sendRetMsg = "成功";
            //return "";
            //  MyTrace.get().debug("QPayBLL.sendRedBag.begin", openid, t_money.ToString(), t_order_no);
            string sendRetCode = ""; //返回码
            sendRetMsg = "";
            string pre_mch_billno = "";
            string pre_mch_id = srpConfig.mch_id;
            string pre_wxappid = srpConfig.wxappid;
            string pre_total_amount = t_money.ToString();
            string pre_re_openid = openid;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");
            pre_mch_billno = DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(10);
            pre_mch_billno = srpConfig.mch_id + pre_mch_billno;
            t_order_no = pre_mch_billno;
            //return "";
            try
            {
                //创建支付应答对象
                RequestHandler packageReqHandler = new RequestHandler();
                packageReqHandler.init();
                //设置package订单参数
                packageReqHandler.setParameter("nonce_str", TenpayUtil.getNoncestr());		//nonce_str
                packageReqHandler.setParameter("mch_billno", pre_mch_billno);		//商家订单号
                packageReqHandler.setParameter("mch_id", pre_mch_id);		  //商户号
                packageReqHandler.setParameter("wxappid", pre_wxappid);		  //商户公众号appid
                packageReqHandler.setParameter("nick_name", srpConfig.title);		  //提供方名称
                packageReqHandler.setParameter("send_name", srpConfig.title);		  //商户名称
                packageReqHandler.setParameter("re_openid", pre_re_openid);		  //openid
                packageReqHandler.setParameter("total_amount", pre_total_amount);		  //付款金额
                packageReqHandler.setParameter("min_value", pre_total_amount);		  //最小红包
                packageReqHandler.setParameter("max_value", pre_total_amount);		  //最大红包
                packageReqHandler.setParameter("total_num", "1");		  //红包发放人数
                packageReqHandler.setParameter("wishing", srpConfig.wishing);		  //红包祝福语 128
                packageReqHandler.setParameter("client_ip", "192.168.6.117");		  //调用方IP地址
                packageReqHandler.setParameter("act_name", srpConfig.act_name);		  //活动名称32
                packageReqHandler.setParameter("remark", srpConfig.remark);		  //活动备注256
                //packageReqHandler.setParameter("logo_imageurl", "");		  //活动LOGO URL http://ds.emoney.cn/chaoguquan/images/jp.png
                packageReqHandler.setParameter("share_content", srpConfig.share_content);		  //分享文案
                packageReqHandler.setParameter("share_url", Config.Host_Url + "Bag2/Index?p_openid=" + openid);		  //分享地址OAuth2Helper.GetAuthorizeUrl(ConfigHelper.Host_Url + "Bag2/Index?p_openid=" + openid,false)
                packageReqHandler.setParameter("share_imgurl", Config.Host_Url + "images/jp.png");//分享LOGO
                packageReqHandler.setKey(srpConfig.paykey);
                string data = packageReqHandler.getXMLData();
                // MyTrace.get().debug("红包debug002");
                string ret = NetHelper.LoadDataPostWithCert(Config.api_redbag_url, null, data, Encoding.GetEncoding("UTF-8"), pre_mch_id, srpConfig.wechat_bag_cert);
                // MyTrace.get().debug("ret:" + ret);
                RequestHandler responseHandler = new RequestHandler();
                responseHandler.setKey(srpConfig.paykey);
                DataSet ds = Common.GetDataSetByXmlData(ret);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        responseHandler.setParameter(dt.Columns[i].ColumnName, dt.Rows[0][i].ToString());
                    }
                    ds.Clear(); ds = null;
                }
                
                //判断协议字段
                string return_code = responseHandler.getParameter("return_code");
                if (return_code != null)
                {
                    if (return_code == "SUCCESS")
                    {
                        ////校验签名
                        //string check_msg = "";
                        //if (responseHandler.checkSign(out check_msg))
                        //{
                        string result_code = responseHandler.getParameter("result_code");
                        if (result_code != null)
                        {
                            if (result_code == "SUCCESS")
                            {
                                string mch_billno = responseHandler.getParameter("mch_billno", false);
                                string mch_id = responseHandler.getParameter("mch_id", false);
                                string wxappid = responseHandler.getParameter("wxappid", false);
                                string re_openid = responseHandler.getParameter("re_openid", false);
                                string total_amount = responseHandler.getParameter("total_amount", false);
                                if (pre_mch_billno == mch_billno && pre_mch_id == mch_id && pre_wxappid == wxappid && pre_re_openid == re_openid && pre_total_amount == total_amount)
                                {
                                    sendRetCode = "";
                                    sendRetMsg = "success";
                                }
                                else
                                {
                                    sendRetCode = "10013";//me
                                    sendRetMsg = "返回参数有变更";
                                }
                            }
                            else
                            {
                                sendRetCode = responseHandler.getParameter("err_code", false);
                                sendRetMsg = responseHandler.getParameter("err_code_des", false);
                            }
                        }
                        else
                        {
                            sendRetCode = "10012";//me
                            sendRetMsg = "找不到result_code";
                        }
                    }
                    else
                    {
                        sendRetCode = return_code;
                        sendRetMsg = responseHandler.getParameter("return_msg", false);
                    }
                }
                else
                {
                    sendRetCode = "10011";//me
                    sendRetMsg = "找不到return_code";
                }
            }
            catch (Exception ex)
            {
                sendRetCode = "10014";//me
                sendRetMsg = ex.Message;
            }
            return sendRetCode;
        }
    }
}
